<template>
  <view class="time-picker">
    <u-picker
      :show="showPicker"
      :columns="timeColumns"
      @confirm="onConfirm"
      @cancel="onCancel"
      title="选择时间"
      :close-on-click-overlay="true"
      :safe-area-inset-bottom="true"
    />
  </view>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'

// 组件属性
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  value: {
    type: String,
    default: ''
  },
  startTime: {
    type: String,
    default: '08:00'
  },
  endTime: {
    type: String,
    default: '18:00'
  },
  interval: {
    type: Number,
    default: 30
  }
})

// 组件事件
const emit = defineEmits(['update:show', 'confirm', 'cancel'])

// 响应式数据
const showPicker = ref(false)

// 生成时间选项
const generateTimeOptions = () => {
  const options = []
  const [startHour, startMinute] = props.startTime.split(':').map(Number)
  const [endHour, endMinute] = props.endTime.split(':').map(Number)
  
  const startMinutes = startHour * 60 + startMinute
  const endMinutes = endHour * 60 + endMinute
  
  for (let minutes = startMinutes; minutes <= endMinutes; minutes += props.interval) {
    const hour = Math.floor(minutes / 60)
    const minute = minutes % 60
    const timeStr = `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`
    options.push({ label: timeStr, value: timeStr })
  }
  
  return options
}

// 时间选项数据
const timeColumns = ref([generateTimeOptions()])

// 监听显示状态
watch(() => props.show, (newVal) => {
  showPicker.value = newVal
})

watch(showPicker, (newVal) => {
  emit('update:show', newVal)
})

// 确认选择
const onConfirm = (event) => {
  console.log('TimePicker确认选择:', event)
  if (event && event.value && event.value.length > 0) {
    const selectedTime = event.value[0]
    emit('confirm', {
      value: selectedTime.value,
      label: selectedTime.label
    })
  }
  showPicker.value = false
}

// 取消选择
const onCancel = () => {
  console.log('TimePicker取消选择')
  emit('cancel')
  showPicker.value = false
}

// 组件挂载时初始化
onMounted(() => {
  console.log('TimePicker组件挂载，开始初始化时间数据')
  timeColumns.value = [generateTimeOptions()]
  console.log('TimePicker初始化完成，选项数量:', timeColumns.value[0].length)
})
</script>

<style lang="scss" scoped>
.time-picker {
  // 组件样式
}
</style>
